package com.financing.platform.task;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.financing.mail.service.MailSenderService;
import com.financing.platform.dto.ProductCheckLogDTO;
import com.financing.platform.dto.ProjectDTO;
import com.financing.platform.service.IProductCheckLogService;
import com.financing.platform.service.IProjectService;
import com.financing.platform.service.ISwitchService;
import com.financing.platform.util.DateUtil;
import com.financing.platform.util.MemcacheCacheHelper;
import com.financing.platform.web.api.ProjectAction;

@Component("autoCheckProjectJob")
public class AutoCheckProjectJob {
	
	protected Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private IProjectService projectService;
	
	@Autowired
	private IProjectService projectServiceImpl;
	
	@Autowired
	private IProductCheckLogService productCheckLogService;
	
	@Autowired
	private ProjectAction projectAction;
	
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Autowired
	private MailSenderService mailSenderService;

	@Autowired
	private ISwitchService switchSerivceImpl;
	
	/***
	 * 金融产品领导审核中  自动审核
	 */
//	@Scheduled(cron = "0 0/5 * * * ?") 
	public void autoCheckProject(){
		
		try {
			//不能自动删除
			Object autoCheckProject=MemcacheCacheHelper.mcc.get("autoCheckProject");
			if(autoCheckProject!=null){
				Date d=(Date)autoCheckProject;
				if(d.before(new Date())){
					MemcacheCacheHelper.mcc.delete("autoCheckProject");
				}
			}
			
			//获取memcache
			Date date = new Date(System.currentTimeMillis()+10*60*1000);
			if(!MemcacheCacheHelper.mcc.add("autoCheckProject",date,date)){
				logger.info("autoCheckProject running");
				return;
			}
			
			//审核状态为4的产品
			ProjectDTO projectDTO=new ProjectDTO();
			projectDTO.setStatus("4");
			projectDTO.setpPublicStatus("1");
			projectDTO.setDeleteTag("1");
			projectDTO.setFlagBaoxiao(false);
			List<ProjectDTO> queryAllProject = projectService.queryAllProject(projectDTO);
			
			for (int i = 0; i < queryAllProject.size(); i++) {
				try {
					ProjectDTO projectDTO2 = queryAllProject.get(i);
					String addCheckTime = projectDTO2.getAddCheckTime();
					if(StringUtils.isBlank(addCheckTime))continue;
					Date parse = sdf.parse(addCheckTime);
					Date current=new Date();
					//如果超过一小时   金融产品自动审核通过 
					if(DateUtil.addHour(parse, 1).before(current)){
						ProjectDTO pro=new ProjectDTO();
						Integer id = projectDTO2.getId();
						pro.setId(id);
						pro.setStatus("5");
						pro.setpPublicStatus("1");
						pro.setAddSaleCheckTime(DateUtil.getDate("yyyy-MM-dd HH:mm:ss"));
						pro.setUpdateBy("systemauto");
						pro.setUpdateDate(new Date());
						projectServiceImpl.updateProject(pro,null);
						//产品部门自动审核通过 邮件短信通知销售部门领导  
						projectAction.sendEmailAndSms(projectDTO2,"2");
						//流水
						insertCheckLog(id,"2");
					}
				} catch (Exception e) {
					Log.error("error autoCheckProject",e);
				}
			}
		} catch (Exception e) {
			Log.error("error autoCheckProject a",e);
		}finally{
			MemcacheCacheHelper.mcc.delete("autoCheckProject");
		}
	}
	
/***
 * 审核流水
 * @param checkType
 * @throws SQLException
 */
	private void insertCheckLog(Integer pId,String checkType) throws SQLException {
		ProductCheckLogDTO productCheckLog=new ProductCheckLogDTO();
		productCheckLog.setProductId(pId);
		productCheckLog.setCheckStatus("1");
		productCheckLog.setCheckType(checkType);
		productCheckLog.setCreateBy("autoSystem");
		productCheckLog.setUpdateBy("autoSystem");
		productCheckLog.setCreateDate(new Date());
		productCheckLog.setUpdateDate(new Date());
		productCheckLog.setDeleteTag("1");
		productCheckLogService.insert(productCheckLog);
	}
	
	/***
	 * 销售部领导审核中  自动审核发布
	 */
//	@Scheduled(cron = "0 0/5 * * * ?") 
	public void autoPulibcProject(){
		//审核状态为5的产品
		ProjectDTO projectDTO=new ProjectDTO();
		projectDTO.setStatus("5");
		projectDTO.setpPublicStatus("1");
		projectDTO.setDeleteTag("1");
		projectDTO.setFlagBaoxiao(false);
		List<ProjectDTO> proList = projectService.queryAllProject(projectDTO);
		
		for (int i = 0; i < proList.size(); i++) {
			try {
				ProjectDTO projectDTO2 = proList.get(i);
				String addSaleCheckTime = projectDTO2.getAddSaleCheckTime();
				if(StringUtils.isBlank(addSaleCheckTime))continue;
				Date parse = sdf.parse(addSaleCheckTime);
				Date current=new Date();
				//如果超过一小时   销售自动审核通过 
				if(DateUtil.addHour(parse, 1).before(current)){
					ProjectDTO pro=new ProjectDTO();
					Integer id = projectDTO2.getId();
					pro.setId(id);
					pro.setStatus("3");
					pro.setpPublicStatus("2");
					pro.setUpdateBy("systemauto");
					pro.setUpdateDate(new Date());
					projectServiceImpl.updateProject(pro,null);
					//流水
					insertCheckLog(id,"4");
				}
			} catch (Exception e) {
				Log.error("error autoPulibcProject",e);
			}
		}
	}
	
	/***
	 * 产品修改价格  发送邮件和短信提醒
	 * 
	 */
	@Scheduled(cron = "0 0/2 * * * ?") 
	public synchronized void autoSend(){
		

		try {
			//不能自动删除
			Object autoSend=MemcacheCacheHelper.mcc.get("autoSend");
			if(autoSend!=null){
				Date d=(Date)autoSend;
				if(d.before(new Date())){
					MemcacheCacheHelper.mcc.delete("autoSend");
				}
			}
			
			//获取memcache
			Date date = new Date(System.currentTimeMillis()+10*60*1000);
			if(!MemcacheCacheHelper.mcc.add("autoSend",date,date)){
				logger.info("autoSend running");
				return;
			}
			
			//修改产品时间
//		public static Map<Integer,Date> updateProductIdMap=new HashMap<Integer,Date>();
			Map<Integer,Date> updateProductIdMap =	(Map<Integer, Date>) MemcacheCacheHelper.mcc.get("updateProductIdMap");
			if(updateProductIdMap!=null){
				List<Integer> sendId=new ArrayList<Integer>();
				for (Entry<Integer,Date> entry:updateProductIdMap.entrySet()) {
					Integer pId = entry.getKey();
					Date upDate = entry.getValue();
					if(DateUtil.addMinute(upDate,10).before(new Date())){
						//根据id查询产品
						ProjectDTO projectDTO=new ProjectDTO();
						projectDTO.setId(pId);
						ProjectDTO queryProject = projectServiceImpl.queryProject(projectDTO);
						//超过10分钟 发送邮件
						projectAction.sendEmailAndSms(queryProject,"3");
						//记录sendId 已发送
						sendId.add(pId);
					}
				}
				//删除已经发送邮件的通知
				for (Integer id : sendId){
					updateProductIdMap.remove(id);
				}
				MemcacheCacheHelper.mcc.set("updateProductIdMap",updateProductIdMap);
			}else{//设置空map
				MemcacheCacheHelper.mcc.set("updateProductIdMap",new HashMap<Integer,Date>());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			MemcacheCacheHelper.mcc.delete("autoSend");
		}
	}
	

}
